package www.dianbaozu.com.ui.server.findMember

import androidx.hilt.lifecycle.ViewModelInject
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import www.wen.com.common.lib.base.module.BaseViewModel
import www.wen.com.common.lib.data.entities.LoadingDialog
import www.wen.com.common.lib.data.entities.LoadingDialogStateType
import www.wen.com.common.lib.data.entities.Result
import www.wen.com.common.lib.data.entities.ServiceMemberListEntity
import www.wen.com.common.lib.data.entities.UiStateCustom
import www.wen.com.common.lib.data.repository.AppDataManager

class FindMemberViewModel @ViewModelInject constructor(private val appDataManager: AppDataManager) :
    BaseViewModel() {

    var page: Int = 0
    var size: Int = 20

    @FlowPreview
    fun searchServerMemberList(
        serverId: String,
        nickName: String,
        action: ((Result.Success<ServiceMemberListEntity>) -> Unit)
    ) {
        viewModelScope.launch {
            appDataManager.getServerMemberListFlow(serverId, nickName, page, size)
                .catch { cause ->
                    loading.value = UiStateCustom(
                        stateData = LoadingDialog(
                            tip = cause.message ?: "网络异常",
                            loadingDialogStateType = LoadingDialogStateType.ERROR,
                            isShowDialogTip = false,
                            isShowToastTip = true
                        )
                    )
                }
                .collect {
                    action.invoke(it)
                    if (it.data.content.isNotEmpty()) {
//                        delay(200)
                        page++
                        searchServerMemberList(serverId, nickName, action)
                    }
                }
        }
    }

}